@tool
@icon("../icons/expression_guard.svg")
class_name ExpressionGuard
extends Guard

# 根据表达式结果决定能否触发
var expression:String = ""

func is_satisfied(transition:Transition,state:State) -> bool:
	var root = state
	while is_instance_valid(root) and not root is FSM:
		root = root.get_parent()
	if not is_instance_valid(root):
		return false
	var temp_expression := Expression.new()
	var input_names = root.expression_properties.keys()
	var parse_result = temp_expression.parse(expression,input_names)
	if parse_result != OK:
		#push_error("Expression parse error: " + temp_expression.get_error_text() + " for expression " + expression)
		return false
	var input_values = []
	for input_name in input_names:
		input_values.append(root.expression_properties[input_name])
	var result = temp_expression.execute(input_values,root.cur_owner)
	if temp_expression.has_execute_failed():
		#push_error("Expression execute error: " + temp_expression.get_error_text() + " for expression: " + expression)
		return false
	if typeof(result) != TYPE_BOOL:
		#push_error("Expression result is not boolean")
		return false
	return result

func _get_property_list() -> Array[Dictionary]:
	var properties:Array[Dictionary] = []
	properties.append({
		"name":"expression",
		"type":TYPE_STRING,
		"usage":PROPERTY_USAGE_DEFAULT,
		"hint":PROPERTY_HINT_EXPRESSION,
	})
	return properties
